package edu.mama.college.service;

import edu.mama.college.mapper.ResourceMapper;
import edu.mama.college.model.JsonResult;
import edu.mama.college.model.Page;
import edu.mama.college.model.Resource;
import edu.mama.college.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import javax.servlet.http.Part;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;

    /**
     * 获取资源列表
     * @param page
     * @param size
     * @param type
     * @return
     */
    public Page<Resource> getResourceList(int page,int size,String type){
        List<Resource> resourceList = resourceMapper.getResourceList(page,size,type);
        int total = resourceMapper.getResourceCount(type);
        return new Page<>(page,size,total,resourceList);
    }


    /**
     * 获取资源列表
     * @param type
     * @return
     */
    public List<Resource> getResourceList(String type){
        return resourceMapper.getResources(type);
    }



    public void create(Resource resource){
        resourceMapper.create(resource);
    }

    /**
     * 删除
     * @param id
     */
    public void delete(int id){
        resourceMapper.delete(id);
    }


    /**
     * 上传文件
     * @param part
     * @param duration
     * @param type
     * @throws Exception
     */
    public void uploadResource(Part part, Number duration, String type) throws Exception {
        Map<String,String> uploadResult ;
        try{
            uploadResult =  FileUtil.uploadFile(part,type);
        }catch(Exception e){
            throw new Exception("上传失败");
        }
        Resource resource = new Resource();
        resource.setName(uploadResult.get("name"));
        resource.setUrl(uploadResult.get("url"));
        resource.setSize( Integer.parseInt(uploadResult.get("size")));
        resource.setType(type);
        if(type.equals("video")){
            resource.setDuration( duration.intValue());
        }
        try{
            this.create(resource);
        }catch(Exception e){
            log.error("数据写入失败：",e);
            throw new Exception("上传失败");
        }
    }

    public void deleteResource(int id) throws Exception{
        try{
            int num = resourceMapper.getNumByStudied(id);
            if(num > 0){
                throw new Exception("该视频资源已经被学生学习，不得删除");
            }
            Resource resource = resourceMapper.selectById(id);
            FileUtil.deleteFile(resource.getUrl());
            this.delete(id);
        }catch(Exception e){
            log.error("删除文件失败",e);
            throw new Exception(e.getMessage());
        }
    }



}
